// 题目链接：https://www.luogu.com.cn/problem/P2658

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cstdlib>
using namespace std;

#define x first
#define y second
typedef pair<int, int> PII;

const int N = 505;
const int M = 505;
int h[M][N];
int g[M][N];
int n, m;

int dx[] = {-1, 0, 0, 1};
int dy[] = {0, -1, 1, 0};

bool BFS(PII s, int d, int target)
{
    bool visited[M][N] = {false};
    queue<PII> q;
    q.push(s);
    visited[s.x][s.y] = true;

    int found = 1;
    while (!q.empty())
    {
        auto t = q.front();
        q.pop();

        for (int i = 0; i < 4; ++i)
        {
            int a = t.x + dx[i];
            int b = t.y + dy[i];

            if (a < 0 || a >= m || b < 0 || b >= n)
                continue;
            if (visited[a][b])
                continue;
            if (abs(h[a][b] - h[t.x][t.y]) > d)
                continue;

            q.push({a, b});
            visited[a][b] = true;
            if (g[a][b] == 1)
            {
                ++found;
                if (found == target)
                    return true;
            }
        }
    }

    return false;
}

int main()
{
    scanf("%d %d", &m, &n);
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            scanf("%d", &h[i][j]);
        }
    }
    int cnt_flag = 0; // 统计路标个数
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            scanf("%d", &g[i][j]);
            if (g[i][j] == 1)
            {
                ++cnt_flag;
            }
        }
    }

    // 找到第一个路标
    bool flag = false;
    PII s;
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            if (g[i][j] == 1)
            {
                s = {i, j};
                flag = true;
                break;
            }
        }
        if (flag)
            break;
    }

    int l = -1, r = 1e9 + 1;
    int mid;
    while (l + 1 < r)
    {
        mid = (l + r) / 2;
        bool res = BFS(s, mid, cnt_flag);
        if (res)
            r = mid;
        else
            l = mid;
    }

    printf("%d\n", r);
    return 0;
}